﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace d39
{
    public static class Base26
    {
        // _a => -1
        // 0 => 0
        // a => 1
        // z => 26
        // Aa => 27
        // Az => 52
        // Ba => 53
        // etc

        // In some contexts (but not handled by this class) a prefix of "5" means ".5", eg 5a = 1.5.

        public static int ParseInt(string str, int start, out int end)
        {
            var result = 0;
            end = start;
            var ch = str[end++];

            if (ch == '0') return 0;

            if (ch == '_')
            {
                var negResult = ParseInt(str, start + 1, out end);
                if (negResult <= 0) throw new ArgumentException("Illegal base26 string");
                return -negResult;
            }

            while (ch >= 'A' && ch <= 'Z')
            {
                result += ((int)ch) - ((int)'A') + 1;
                result *= 26;
                ch = str[end++];
            }
            if (ch >= 'a' && ch <= 'z')
            {
                return result + ((int)ch) - ((int)'a') + 1;
            }
            throw new ArgumentException("Illegal base26 character");
        }

        public static string IntToString(int num)
        {
            if (num == 0) return "0";
            if (num < 0) return '_' + IntToString(-num);

            num--;

            if (num >= 26)
            {
                return IntToString(num / 26).ToUpper() + ((char)('a' + num % 26));
            }
            else
            {
                return ((char)('a' + num % 26)).ToString();
            }
        }

        internal static bool IsValidChar(string str, int start)
        {
            return start < str.Length &&
                (str[start] == '0' || str[start] == '_' ||
                 (str[start] >= 'A' && str[start] <= 'Z') ||
                 (str[start] >= 'a' && str[start] <= 'z'));
        }
    }
}